<?php
class DiyImage {
  var $max_width = 120;
  var $max_height = 120;
  var $standard_width = 300;


  function DiyImage() {}

  function moveResizedImage($filename, $path) {
    $img_info = getimagesize($filename);    
    $width = $img_info[0];
    $height = $img_info[1];


    if ($width > $this->standard_width) {
      $ratio = $width/$height;
      $new_width = $this->standard_width;
      $new_height = $this->standard_width / $ratio;
    } else {
      $new_width = $width;
      $new_height = $height;
    }

    switch ($img_info['mime']) {
    case "image/gif":
    case "image/jpeg":
    case "image/png":
    case "image/psd":
      $type = explode("/", $img_info['mime']);
      $type = $type[1];
      break;
    default :
      $type = "";
    }

    if ($type == "") {
      die($type);
      return false;
    }

    if ($type == "psd")
      $type = "png";

    $new_img = imagecreatetruecolor($new_width, $new_height);
    $source = call_user_func('imagecreatefrom' . $type, $filename);

    imagecopyresized($new_img, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagejpeg($new_img, $path);
    return true;
  }

  function makeThumbnail($filename, $path) {
    $filename = realpath($filename);
    $img_info = getimagesize($filename);
    $width_orig = $img_info[0];
    $height_orig = $img_info[1];

    $ratio_orig = $width_orig/$height_orig;

    if ($this->max_width/$this->max_height > $ratio_orig) {
      $this->max_width = $this->max_height*$ratio_orig;
    } else {
      $this->max_height = $this->max_width/$ratio_orig;
    }

    switch ($img_info['mime']) {
    case "image/gif":
    case "image/jpeg":
    case "image/png":
    case "image/psd":
      $type = explode("/", $img_info['mime']);
      $type = $type[1];
      break;
    default :
      $type = "";
    }

    if ($type == "") {
      die($type);
      return false;
    }

    if ($type == "psd")
      $type = "png";

    $thumb = imagecreatetruecolor($this->max_width, $this->max_height);
    $source = call_user_func('imagecreatefrom' . $type, $filename);

    // Resize
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $this->max_width, $this->max_height, $width_orig, $height_orig);

    // Output
    imagejpeg($thumb, $path);
    return true;
  }
}

?>
